import {message} from 'antd';
import Event from 'events';
import assign from 'object-assign';
import AppDispatcher from './TableDispatcher';
import TableConstants from './TableConstants';
const EventEmitter = Event.EventEmitter;
const CHANGE_EVENT = 'change';

function fliter4error(datas) {
    message.error("接口发生异常，错误代码["+datas.error+"]，错误信息["+datas.msg+"]！",3);
}

const datas4false = {status:"false",msg:"接口程序异常",error:"000"};

let options = {};
let allDatas = [];
let datas = [];
let count = 0;
let loading = false;
let msg = "";
let haveAllData = false;
let tmpKey = "";
let searching = false;
let page = {
    maxNum:1,
    nowPage:1,
    maxPage:1,
    pageNum:10,
    nowMinNum:1,
    nowMaxNum:1,
    getMaxNum() {
        return this.maxNum;
    },
    setMaxNum(maxNum) {
        this.maxNum = maxNum;
        this.maxPage = parseInt(this.maxNum/this.pageNum)+(this.maxNum%this.pageNum!=0?1:0); //计算页数
        //console.log("maxPage:"+this.maxPage+" maxNum:"+this.maxNum);
    },
    getNowPage() {
        return this.nowPage;
    },
    setNowPage(nowPage) {
        this.nowPage = nowPage;
        this.nowMaxNum = this.maxNum<this.nowPage*this.pageNum?this.maxNum:(this.nowPage*this.pageNum);
        this.nowMinNum = this.nowPage>1?(this.nowPage-1)*this.pageNum+1:1;
        //this.nowMinNum = nowMaxNum-pageNum+1;
    },
    getMaxPage() {
        return this.maxPage;
    },
    getPageNum() {
        return this.pageNum;
    },
    setPageNum(pageNum) {
        this.pageNum = pageNum;
    },
    getNowMinNum() {
        return this.nowMinNum;
    },
    getNowMaxNum() {
        return this.nowMaxNum;
    }
};

const TableStore = assign({}, EventEmitter.prototype, {
  	getDatas() {
        if(!haveAllData)
  	        return datas;
        else {
            //console.log(" min:"+(page.nowMinNum-1)+" max:"+page.nowMaxNum);
            return datas.slice(page.nowMinNum-1,page.nowMaxNum);
        }
    },
    getPage() {
        return page;
    },
    getLoading() {
        return loading;
    },
    getMsg() {
        return msg;
    },
    getHaveAllData() {
        return haveAllData;
    },
    getQuickSearch() {
        return options.quickSearch;
    },
  	emitChange() {
      	this.emit(CHANGE_EVENT);
  	},
  	addChangeListener(callback) {
  		this.on(CHANGE_EVENT, callback);
  	},
  	removeChangeListener(callback) {
  		this.removeListener(CHANGE_EVENT, callback);
  	}
});

function doSearchAll() {
    $.ajax({
        type:"POST",
        url:options.dataUrl+"&"+$("#"+options.formId).serialize(),
        success(edatas) {
           if(edatas.status!="false") {
              const data = edatas;
              datas = data;
              allDatas = data;
              page.setPageNum(options.pageNum);
              page.setMaxNum(count);
              page.setNowPage(1);
              haveAllData = true;
              loading = false;
              TableStore.emitChange(CHANGE_EVENT); //触发回调事件
           }
           else {
              fliter4error(edatas);
           }
        },
        error(edatas) {
            fliter4error(datas4false);
        },
        dataType: "json"
    });
}

function doSearch(min,max,now) {
    if(count==0) {
        //console.log("options:",options);
        //console.log("url:"+options.numUrl);
        $.ajax({
            type:"POST",
            url:options.numUrl+"&"+$("#"+options.formId).serialize(),
            success(edatas) {
                if(edatas.status!="false") {
                      const data = edatas;
                      count = data;
                      if(count>options.maxSearchNum) {
                          options.quickSearch = false;
                      }
                      else {
                          options.quickSearch = true;
                      }
                      doSearchData(min,max,now);
                }
                else {
                    fliter4error(edatas);
                }
            },
            error(datas) {
                fliter4error(datas4false);
            },
            dataType: "json"
        });
    }
    else {
         doSearchData(min,max,now);
    }
}

function doSearchData(min,max,now) {
    //console.log("now:"+now);
    //console.log("url:"+options.dataUrl+"&"+$("#"+options.formId).serialize()+"&min="+min+"&max="+max);
  	$.ajax({
        type:"POST",
        url:options.dataUrl+"&"+$("#"+options.formId).serialize()+"&min="+min+"&max="+max,
        success(edatas) {
            if(edatas.status!="false") {
                const data = edatas;
                datas = data;
                //console.log("datas:"+datas);
                //console.log("options.quickSearch:"+options.quickSearch);
                if(!options.quickSearch) {
                    page.setPageNum(options.pageNum);
                    page.setMaxNum(count);
                    page.setNowPage(now);
                    loading = false;
                    TableStore.emitChange(CHANGE_EVENT);
                }
                haveAllData = false;
                if(options.quickSearch) {
                    msg = "正在获取数据[所有]...";
                    TableStore.emitChange(CHANGE_EVENT); //触发回调事件
                    doSearchAll();
                }
            }
            else {
                fliter4error(edatas);
            }
        },
        error(datas) {
            fliter4error(datas4false);
        },
        dataType: "json"
      });
}

function filter(key) {
    searching = true;
    if(key==""||key==null) {
        datas = allDatas;
    }
    else {
        datas = [];
        let flag = 0;
        for(let i=0;i<allDatas.length&&searching;i++) {
            let data = allDatas[i];
            let find = false;
            //console.log("columns.length:"+options.columns.length);
            for(let j=0;j<options.columns.length&&searching&&!find;j++) {
                //console.log("name:"+);
                const dataIndex = options.columns[j].dataIndex;
                if(dataIndex!="") {
                    let value = eval("data."+options.columns[j].dataIndex);
                    if(typeof(value)=="string") {
                        if(value.indexOf(key)>=0) {
                            //console.log("value:"+value+" key:"+key);
                            datas[flag++] = data;
                            find = true;
                        }
                    }
                }
            }
        }
    }
}

function doQuickSearch(action) {
    let key = action.key;
    //console.log("key:"+key+" tmpKey:"+tmpKey);
    if(tmpKey==key) {
        return ;
    }
    tmpKey = key;
    filter(key);
    if(!searching) return ;
    page.setMaxNum(datas.length);
    page.setNowPage(1);
    loading = false;
    TableStore.emitChange(CHANGE_EVENT);
}

function doExcelOut() {
    $.ajax({
        type:"POST",
        url:options.excelOutUrl+"&"+$("#"+options.formId).serialize(),
        success(edata) {
            if(edatas.status!="false") {
                const data = edatas;
                loading = false;
                TableStore.emitChange(CHANGE_EVENT);
                try {
                    //console.log(data);
                    window.open(data);
                }catch(e) {console.log(e);}
            }
            else {
                fliter4error(edatas);
            }
        },
        error(data) {
            fliter4error(datas4false);
            //console.log(data);
        },
        dataType: "html"
    });
}

AppDispatcher.register(function(action) {
    switch(action.actionType) {
        case TableConstants.TABLE_SEARCH:
            options = action.options;
            loading = true;
            msg = "正在获取数据[第一页]...";
            TableStore.emitChange(CHANGE_EVENT); //触发回调事件
            count = 0;
            doSearch(1,page.pageNum,1);
        break;
        case TableConstants.TABLE_GOPAGE:
            loading = true;
            msg = "正在获取数据[分页]...";
            TableStore.emitChange(CHANGE_EVENT); //触发回调事件
            page.setPageNum(options.pageNum);
            page.setMaxNum(count);
            page.setNowPage(action.newPage);
            //console.log("options.pageNum:"+options.pageNum);
            //console.log("count:"+count);
            //console.log("action.newPage:"+action.newPage);
            if(!options.quickSearch) {
                //count = 0;
                doSearch(page.nowMinNum,page.nowMaxNum,action.newPage);
            }
            else {
                loading = false;
                TableStore.emitChange(CHANGE_EVENT); //触发回调事件
            }
        break;
        case TableConstants.TABLE_SEARCHBYKEY:
            if(options.quickSearch) {
                searching = false;
                //quickSearch(action);
                doQuickSearch(action);
            }
        break;
        case TableConstants.TABLE_SETOPTIONS:
            options = action.options;
            //console.log("columns.length:"+options.columns.length);
        break;
        case TableConstants.TABLE_EXCELOUT:
            loading = true;
            TableStore.emitChange(CHANGE_EVENT); //触发回调事件
            doExcelOut();
        break;
        default:
    }
});

export default TableStore;